<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 卡片头部 -->
      <div class="box-card-input">
        <el-input size="small" placeholder="用户名" v-model="username">
        </el-input>
        <el-input size="small" placeholder="姓名" v-model="name"> </el-input>
        <el-select
          v-model="status"
          style="margin-right: 5px"
          placeholder="状态"
          clearable
        >
          <!-- <el-option label="全部" value="all"></el-option> -->
          <el-option label="有效" value="1"></el-option>
          <el-option label="无效" value="0"></el-option>
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy 年 MM 月 dd 日"
        >
        </el-date-picker>

        <div class="box-card-button">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="queryUserBySearch"
            >搜索</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="add = true"
            >新增</el-button
          >
          <el-button
            type="danger"
            @click="openBatchDel"
            size="small"
            icon="el-icon-delete"
            >批量删除</el-button
          >
          <el-button type="primary" size="small" @click="imports = true"
            >导入<i class="el-icon-upload el-icon--right"> </i
          ></el-button>
          <el-button type="primary" size="small" @click="exportUser"
            >导出<i class="el-icon-download el-icon--right"> </i
          ></el-button>
        </div>
      </div>

      <!-- 卡片表格区 -->
      <!-- <el-empty description="信息为空" v-if="tableData.length === 0"></el-empty> -->

      <div class="box-card-table">
        <el-table
          :data="tableData"
          @selection-change="tableDataChange"
          ref="multipleTable"
          border
          style="width: 100%"
        >
          <el-table-column width="50" type="selection" align="center">
            <!-- <el-checkbox v-model="checked"></el-checkbox> -->
          </el-table-column>
          <el-table-column prop="id" width="100" label="序号" align="center">
          </el-table-column>
          <el-table-column prop="username" label="用户名" align="center">
          </el-table-column>
          <el-table-column prop="name" label="姓名" align="center">
          </el-table-column>
          <el-table-column prop="gender" label="性别" align="center">
          </el-table-column>
          <el-table-column
            prop="telephone"
            label="电话"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180" align="center">
          </el-table-column>
          <el-table-column
            prop="startTime"
            label="创建时间"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="endTime"
            label="最后修改时间"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <!-- eslint-disable -->
            <template slot-scope="scope">
              <el-tooltip
                :content="'当前状态: ' + transformStatus(scope.row)"
                placement="top"
              >
                <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="1"
                  inactive-value="0"
                  @change="statusChange(scope.row)"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="remarks"
            label="备注"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            class="operation"
          >
            <!-- eslint-disable -->
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="修改"
                placement="left-start"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="openUpdate(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="设置角色"
                placement="left-start"
              >
                <el-button
                  type="success"
                  icon="el-icon-check"
                  @click="openRoler(scope.row)"
                  circle
                ></el-button>
              </el-tooltip>

              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="left-start"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="del(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          @current-change="pageChange"
          @prev-click="prev"
          @next-click="next"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 弹出层 -->

    <div class="add">
      <el-dialog title="新增信息" :visible.sync="add" width="40%">
        <div class="add-form">
          <el-form
            ref="addForm"
            :rules="userRules"
            :model="addForm"
            label-width="80px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="addForm.gender">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="电话" prop="telephone">
              <el-input v-model="addForm.telephone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="addForm.status" placeholder="状态">
                <el-option label="有效" value="1"></el-option>
                <el-option label="无效" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="addForm.remarks"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="add = false">取 消</el-button>
          <el-button type="primary" @click="addinfo">提 交</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 导入弹出层 -->
    <div class="imports">
      <el-dialog title="提示" :visible.sync="imports" :before-close="handleClose" width="50%">
        <div class="imports-form">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="http://localhost:8080/api/user/import"
            :on-preview="handlePreview"
            name="multipartFile"
            :on-remove="handleRemove"
            :file-list="multipartFile"
            :on-success="upSuccess"
            :on-error="upError"
            :headers="header"
            :auto-upload="false"
            
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <el-button
              style="margin-left: 10px"
              size="small"
              type="success"
              @click="submitUpload"
              >上传到服务器</el-button
            >
            <el-button size="small" type="primary" @click="uploadmoBan"
              >下载模板</el-button
            >
            <div slot="tip" class="el-upload__tip">
              注意只能上传相关模板对应的文件，请下载模板查看
            </div>
          </el-upload>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="imports = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 修改弹出层 -->
    <div>
      <el-dialog title="修改信息" :visible.sync="update" width="40%">
        <div class="update-form">
          <el-form
            ref="updateForm"
            :rules="userRules"
            :model="updateForm"
            label-width="80px"
          >
            <el-form-item label="用户名">
              <el-input v-model="updateForm.username"></el-input>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="updateForm.name"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="updateForm.gender">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="updateForm.telephone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="updateForm.email"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                width="250px"
                v-model="updateForm.status"
                placeholder="状态"
              >
                <el-option label="有效" value="1"></el-option>
                <el-option label="无效" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="updateForm.remarks"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="update = false">取 消</el-button>
          <el-button type="primary" @click="updateinfo">提 交</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 设置角色弹出层 -->
    <div>
      <el-dialog :title="this.getName" :visible.sync="roler" width="70%" center>
        <div>
          <el-table
            :data="rolerData"
            @selection-change="rolesSelectionChange"
            ref="rolesDate"
            border
            style="width: 100%"
          >
            <el-table-column width="50" type="selection" align="center">
            </el-table-column>
            <el-table-column prop="id" label="序号" align="center">
            </el-table-column>
            <el-table-column prop="rolerId" label="角色编码" align="center">
            </el-table-column>
            <el-table-column prop="rolerName" label="角色名称" align="center">
            </el-table-column>
            <el-table-column
              prop="startTime"
              label="创建时间"
              width="150"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="endTime"
              label="失效时间"
              width="150"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="rolerStatus" label="状态" align="center">
              <!-- eslint-disable -->
              <template slot-scope="scope">
                <el-switch
                  disabled
                  v-model="scope.row.rolerStatus"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="1"
                  inactive-value="0"
                >
                </el-switch>
              </template>
            </el-table-column>
          </el-table>
          <div class="page">
            <el-pagination
              @size-change="handleSizeChange"
              :current-page="rolerPage"
              :page-sizes="rolerPageSizes"
              :page-size="rolerPageSize"
              @current-change="rolerPageChange"
              @prev-click="roelrPrev"
              @next-click="rolerNext"
              layout="total, sizes, prev, pager, next, jumper"
              :total="rolerTotal"
            >
            </el-pagination>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roler = false">取 消</el-button>
          <el-button type="primary" @click="submitRoler">提 交</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import has from "../../directives/has.js";
export default {
  directives: {
    has,
  },
  inject: ["reload"],
  data() {
    return {
      header: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      rolesDate: [],
      multipleSelection: [],
      roler: false,
      multipartFile: [],
      update: false,
      imports: false,
      add: false,
      date: [],
      value: true,
      checked: true,
      username: "",
      name: "",
      status: "",
      currentPage: 1,
      rolerPage: 1,
      total: 1,
      rolerTotal: 1,
      pageSize: 4,
      rolerPageSize: 4,
      pageSizes: [4, 5, 6, 7, 8],
      rolerPageSizes: [4, 5, 6, 7, 8],
      tableData: [],
      rolerData: [],
      idList: [],
      addForm: {
        username: "",
        password: "",
        name: "",
        gender: "",
        telephone: "",
        email: "",
        status: "1",
        remarks: "",
      },
      updateForm: {
        id: "",
        username: "",
        name: "",
        gender: "",
        telephone: "",
        email: "",
        status: "",
        remarks: "",
      },
      rolerInfo: [],
      getUserId: 0,
      getName: "",
      userRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个英文字母或汉字",
            trigger: "blur",
          },
        ],
        password: [
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个英文字母或汉字",
            trigger: "blur",
          },
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        telephone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          // { type: "number", message: "电话必须为数字值" },
        ],
        // email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
      },
    };
  },
  created() {
    // this.animate = "animate__animated animate__fadeIn";
    this.getData();
  },
  methods: {
     handleClose(done) {
      this.reload();
     },
    //下载模板
    uploadmoBan: function () {
      this.$axios
        .get("api/user/uploadMoBan", { responseType: "arraybuffer" })
        .then((res) => {
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "用户信息模板.xlsx");
          document.body.appendChild(link);
          link.click();
        });
    },
    //显示状态值
    transformStatus: function (row) {
      if (row.status === "1") {
        return "有效";
      }
      return "无效";
    },
    //表格多选相关函数
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //批量删除对话框
    openBatchDel() {
      this.$confirm("此操作将永久删除信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post("/api/user/userBatchDelete", this.idList)
            .then((response) => {
              console.log(response);
              if (response.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.reload();
              } else {
                this.$message({
                  showClose: false,
                  type: "warning",
                  message: response.data.message,
                  duration: 2000,
                });
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //批量删除
    tableDataChange(val) {
      let temp = [];
      console.log(val);
      val.forEach((element) => {
        temp.push(element.id);
      });
      this.idList = Array.from(new Set(temp));
      console.log(this.idList);
    },
    //角色多选框函数
    handleSelectionChange(val) {},
    rolesSelectionChange: function (val) {
      this.rolesDate = val;
      this.rolerInfo = this.rolesDate;
      // console.log(this.rolerInfo);
    },
    //提交用户设置角色信息
    submitRoler: function () {
      let roles = {
        userId: this.getUserId,
        rolerInfo: this.rolerInfo,
      };
      console.log(roles);
      this.$axios
        .post("/api/user/setRoles", roles)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message({
              showClose: false,
              type: "success",
              message: "用户角色设置成功!",
              duration: 1000,
            });
          } else {
            this.$message({
              showClose: false,
              type: "warning",
              message: response.data.message,
              duration: 2000,
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //搜索相关函数
    queryUserBySearch: function () {
      let startTime = null;
      let endTime = null;
      if (this.date !== null) {
        startTime = this.date[0];
        endTime = this.date[1];
      }
      let query = {
        username: this.username,
        name: this.name,
        status: this.status,
        startTime: startTime,
        endTime: endTime,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      };

      this.$axios
        .post("api/user/queryUserBySearch", query)
        .then((response) => {
          console.log(response);
          this.tableData = response.data.data;
          this.total = response.data.total;
          console.log(this.total);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //上传有关函数

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    upSuccess(res) {
      console.log(res);
      this.$message({
        showClose: false,
        type: "success",
        message: res.message,
        duration: 2000,
      });
    },
    upError() {
      this.$message({
        showClose: false,
        type: "warning",
        message: "上传失败!",
        duration: 2000,
      });
    },
    //导出函数
    exportUser: function () {
      this.$axios
        .post("api/user/export", this.idList, { responseType: "arraybuffer" }) //{ responseType: "arraybuffer" }
        .then((res) => {
          if (res.data.code === 4000) {
            this.$message({
              showClose: false,
              type: "warning",
              message: res.data.message,
              duration: 1000,
            });
          } else {
            const url = window.URL.createObjectURL(new Blob([res.data]));
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", "用户信息.xlsx");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        });
    },
    //每页数据展示条数改变函数
    handleSizeChange: function (val) {
      this.queryUserBySearch();
    },
    //当前页改变函数

    pageChange(currentPage) {
      this.currentPage = currentPage;
      this.queryUserBySearch();
    },
    prev() {
      this.currentPage--;
      this.queryUserBySearch();
    },
    next() {
      this.currentPage++;
      this.queryUserBySearch();
    },

    rolerPageChange(currentPage) {
      this.rolerPage = currentPage;
      this.getRolesData();
    },
    roelrPrev() {
      this.rolerPage--;
      this.getRolesData();
    },
    rolerNext() {
      this.rolerPage++;
      this.getRolesData();
    },

    //获取数据函数
    getData: function () {
      this.$axios
        .get("/api/user/queryUser", {
          params: {
            count: this.pageSize,
            currentPage: this.currentPage,
          },
        })
        .then((response) => {
          this.tableData = response.data.data;
          this.total = response.data.total;
          console.log(this.total);
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //增加数据函数
    addinfo: function () {
      this.$axios
        .post("/api/user/insertUser", this.addForm)
        .then((response) => {
          console.log(response);
          if (response.data.code === 200) {
            this.$message({
              showClose: false,
              type: "success",
              message: "添加信息成功!",
              duration: 1000,
            });
            this.add = false;
            this.reload();
          } else {
            this.$message({
              showClose: false,
              type: "warning",
              message: response.data.message,
              duration: 2000,
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //更新数据函数
    openUpdate: function (row) {
      this.update = true;
      this.updateForm = {
        id: row.id,
        username: row.username,
        name: row.name,
        gender: row.gender,
        telephone: row.telephone,
        email: row.email,
        status: row.status,
        remarks: row.remarks,
      };
    },
    updateinfo: function () {
      this.$axios
        .post("/api/user/updateUser", this.updateForm)
        .then((response) => {
          // console.log(response);
          if (response.data.code === 200) {
            this.$message({
              showClose: false,
              type: "success",
              message: "修改信息成功!",
              duration: 1000,
            });
            this.update = false;
            this.reload();
          } else {
            this.$message({
              showClose: false,
              type: "warning",
              message: response.data.message,
              duration: 2000,
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //删除数据函数
    del: function (row) {
      this.$confirm("此操作将永久删除信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post("/api/user/deleteUser", row.id)
            .then((response) => {
              console.log(response);
              if (response.data.code === 200) {
                this.$message({
                  showClose: false,
                  type: "success",
                  message: "删除信息成功!",
                  duration: 1000,
                });
                this.reload();
              } else {
                this.$message({
                  showClose: false,
                  type: "warning",
                  message: response.data.message,
                  duration: 2000,
                });
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //
    getRolesData: function () {
      this.$axios
        .get("/api/roler/queryRoler", {
          params: {
            count: this.rolerPageSize,
            currentPage: this.rolerPage,
          },
        })
        .then((response) => {
          this.rolerData = response.data.data;
          this.rolerTotal = response.data.total;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //打开用户角色设置弹窗
    openRoler: function (row) {
      this.getUserId = row.id;
      this.getName = "设置用户" + row.name + "的角色";
      let arr = [];
      this.$nextTick(async () => {
        const { data: resp } = await this.$axios.get("/api/roler/queryRoler", {
          params: {
            count: this.rolerPageSize,
            currentPage: this.rolerPage,
          },
        });
        console.log(resp);
        this.rolerData = resp.data;
        this.rolerTotal = resp.total;
        console.log(this.rolerData);

        const { data: res } = await this.$axios.post(
          "/api/user/queryRolerById",
          row.id
        );
        console.log(res);

        this.rolerData.forEach((item) => {
          res.data.forEach((el) => {
            if (item.id === el.rolerId) {
              arr.push(item);
              console.log(arr);
            }
          });
        });

        console.log(arr);
        // console.log(this.$refs);

        if (arr) {
          arr.forEach((row) => {
            this.$refs.rolesDate.toggleRowSelection(row, true);
          });
        }
      });
      this.roler = true;
    },
    //修改状态
    statusChange: function (row) {
      (this.updateForm = {
        id: row.id,
        username: row.username,
        name: row.name,
        gender: row.gender,
        telephone: row.telephone,
        email: row.email,
        status: row.status,
        remarks: row.remarks,
      }),
        this.$axios
          .post("/api/user/updateStatus", this.updateForm)
          .then((response) => {
            if (response.data.code === 200) {
              this.$message({
                type: "success",
                message: "修改成功",
              });
              this.reload();
            } else {
              this.$message({
                showClose: false,
                type: "warning",
                message: response.data.message,
                duration: 2000,
              });
            }
          })
          .catch((error) => {
            console.log(error);
          });
    },
  },
};
</script>

<style scoped>
.box-card .box-card-input {
  margin-bottom: 15px;
}
.box-card .box-card-input .el-input {
  display: inline-block;
  width: 200px;
  margin-right: 15px;
  margin-bottom: 10px;
}

.el-form .el-input {
  width: 250px;
}

.el-form .el-select {
  width: 250px;
}
</style>